/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.file.rest;

import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.file.domain.File;
import me.zhengjie.modules.file.service.FileService;
import me.zhengjie.modules.file.service.dto.FileQueryCriteria;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;

import java.io.*;
import java.net.URLEncoder;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @author FireWork
* @date 2021-04-02
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "api/file管理")
@RequestMapping("/api/file")
public class FileController {

    private final FileService fileService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('file:list')")
    public void download(HttpServletResponse response, FileQueryCriteria criteria) throws IOException {
        fileService.download(fileService.queryAll(criteria), response);
    }

//    @GetMapping
//    @Log("查询api/file")
//    @ApiOperation("查询api/file")
//    @PreAuthorize("@el.check('file:list')")
//    public ResponseEntity<Object> query(FileQueryCriteria criteria, Pageable pageable){
//            System.out.println("分页管理");
//        System.out.println(pageable);
//        return new ResponseEntity<>(fileService.queryAll(criteria,pageable),HttpStatus.OK);
//    }

    @PostMapping
    @Log("新增api/file")
    @ApiOperation("新增api/file")
    @PreAuthorize("@el.check('file:add')")
    public ResponseEntity<Object> create( @RequestBody File resources){
        System.out.println(resources);
        return new ResponseEntity<>(fileService.create(resources),HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改api/file")
    @ApiOperation("修改api/file")
    @PreAuthorize("@el.check('file:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody File resources){
        fileService.update(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除api/file")
    @ApiOperation("删除api/file")
    @PreAuthorize("@el.check('file:del')")
    @DeleteMapping
    public ResponseEntity<Object> delete(@RequestBody Integer[] ids) {
        fileService.deleteAll(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @GetMapping
    @Log("查看api/publicFile")
    @ApiOperation("查看api/publicFile")
    @AnonymousAccess
    public ResponseEntity<Object> list(Pageable pageable){
//        System.out.println("公开文件");
//        Sort sort=Sort.by(Sort.Direction.DESC,"audienceId");
//        Pageable pageable1=PageRequest.of(pageable.getPageNumber(),pageable.getPageSize(),sort);
        return new ResponseEntity<>(fileService.findPublicFile(pageable),HttpStatus.OK);
    }


    @GetMapping("/downPublicFile")
    @ApiOperation("下载api/downPublicFile")
    @AnonymousAccess
    public void downPublicFile(@RequestParam String fId,HttpServletResponse response) throws IOException {
        Integer id= Integer.valueOf(fId);
        Integer loginId = null;
        Map map=fileService.verifyFileDownload(loginId,id);
        System.out.println(map);
        String path="";
        if(!map.isEmpty()){
            path=map.get("path").toString();
            java.io.File file=new java.io.File(path);
            if(!file.exists()){
                System.out.println("文件不存在");
            }else {
                System.out.print(file);
            }
            OutputStream os = response.getOutputStream();
            String fileName=map.get("name").toString();
            response.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
            response.setContentType("content-type:octet-stream");
            BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
            OutputStream outputStream = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0 ;
            while ((len = inputStream.read(buffer)) != -1){
                outputStream.write(buffer ,0 , len);
            }
            inputStream.close();
            outputStream.close();
        }else{
            System.out.println("抱歉，你没有该文件的下载权限");
        }
    }

}
